import axios from 'axios'
import store from '@/store'
import router from '@/router'
import { Message } from 'element-ui'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    const token = store.state.user.token
    // 判断有无token
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }

)

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    // 判断后台返回的success
    if (response.data.success === true) {
      return response.data
    } else {
      return Promise.reject(new Error(response.data.message))
    }
  },
  async(error) => {
    console.dir(error)
    if (error.response.data.code === 10002) {
      // token过期  清空token和userInfo 类似与退出
      await store.dispatch('user/userLogout')
      Message.success('请重新登录')
      router.push('/login')
    }
    return Promise.reject(error)
  }
)
export default service
